package cn.zyjw.controller;

import cn.zyjw.domain.SysRole;
import cn.zyjw.model.R;
import cn.zyjw.service.SysRoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Arrays;

@RestController
@Api("角色管理")
@RequestMapping("/roles")
public class SysRoleController {

    @Autowired
    private SysRoleService sysRoleService;

    @GetMapping
    @ApiOperation("角色管理-分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "size", value = "每页显示条数"),
            @ApiImplicitParam(name = "name", value = "查询条件-角色名称"),
    })
    @PreAuthorize("hasAuthority('sys_role_query')")
    public R<Page<SysRole>> findByPage(@ApiIgnore Page<SysRole> page, String name) {
        page.addOrder(OrderItem.desc("last_update_time"));
        Page<SysRole> sysRolePage = sysRoleService.page(page,
                new LambdaQueryWrapper<SysRole>()
                        .like(!StringUtils.isEmpty(name), SysRole::getName, name)
        );
        return R.ok(sysRolePage);
    }

    @PostMapping
    @ApiOperation("新建角色权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysRole", value = "sysRole json对象")
    })
    @PreAuthorize("hasAuthority('sys_role_create')")
    public R add(@RequestBody @Validated SysRole sysRole) {
        boolean save = sysRoleService.save(sysRole);
        if (save) {
            return R.ok("新增成功");
        }
        return R.fail("新增失败");
    }


    @PostMapping("/delete")
    @ApiOperation("角色管理-删除角色")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "删除的权限id集合")
    })
    @PreAuthorize("hasAuthority('sys_role_delete')")
    public R delete(@RequestBody String[] ids) {
        if (ids == null && ids.length == 0) {
            return R.fail("要删除的数据不能为空");
        }
        boolean b = sysRoleService.delRole(Arrays.asList(ids));
        if (b) {
            return R.ok("删除成功");
        }
        return R.fail("删除失败");
    }

}
